<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2023 yoncron All rights reserved.
// +----------------------------------------------------------------------
// | Author: yoncron <yoncron@163.com>
// +----------------------------------------------------------------------
namespace support\exception;

use app\common\Util;
use think\facade\Db;
use Webman\Http\Request;
use Webman\Http\Response;
use Throwable;
use Webman\Exception\ExceptionHandler;

/**
 * Class Handler
 * @package support\exception
 */
class Handler extends ExceptionHandler
{
    public $dontReport = [
        BusinessException::class,
    ];

    public function report(Throwable $exception)
    {
        parent::report($exception);
    }

    public function render(Request $request, Throwable $exception) : Response
    {
        $req = $request->all();
        Util::send_error_msg(json_encode($req));
        $msg = $exception->getMessage();
        preg_match("/(?<=Integrity constraint violation: )[^ ]+/u", $msg, $code);
        if($code && $code[0]==1451){
            preg_match("/(?<=a foreign key constraint fails \(`flower`.`)[^`, CONSTRAINT]+/u", $msg, $table_name);
            $res = Db::query("SELECT TABLE_COMMENT FROM information_schema.tables WHERE TABLE_NAME ='".$table_name[0]."'");
            $TABLE_COMMENT = $res[0]['TABLE_COMMENT']?:'其它业务';
            return error(1,"已被".$TABLE_COMMENT."引用，无法删除。");
        }
        if($code && $code[0]==1062){
            return error(1,"相同数据已存在");
        }
        $client_ip = $request->getRealIp($safe_mode=true);
        $controller = $request->controller;
        $action = $request->action;
        Util::send_error_msg("File:".$exception->getFile()." [".$exception->getLine()."]\r\nController:".$controller."\r\nAction:".$action."\r\nMsg:".$exception->getMessage()."\r\nIP:".$client_ip,'#FE4A26');
        return error(1,"500,系统错误.");
    }

}